import axios from 'axios'
import { getToken } from '@/utils/storage'
import { message} from 'antd'

import eventBus from '@/utils/eventBus' 
let navigate= "";
let store = {}
eventBus.$on((propsObj) => {
  navigate = propsObj;
}, 'axiosInterceptorsFun');
eventBus.$on((propsObj) => {
  store = propsObj;
}, 'store');
const instance = axios.create({
  baseURL: 'http://geek.itheima.net/',
  timeout: 5000
})

instance.interceptors.request.use(
  (config) => {
    const token = getToken()
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

instance.interceptors.response.use(
  (response) => {
    return response.data
  },
  async (error) => {
    if (error.response.status === 401) {
      await store.storeLogin.delToken()
      await store.storeUser.delInfo()
      navigate('/login')
      message.error('token失效')
    } else {
      message.error(error.message || "未知错误")
    }
    return Promise.reject(error)
  }
)

export default instance
